package cn.edu.cqupt.controller;

import cn.edu.cqupt.po.User;
import cn.edu.cqupt.service.UserService;
import cn.edu.cqupt.until.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * @author Andrew
 * @date 2018/1/18
 */
@Controller
@CrossOrigin(origins = "*")
@RequestMapping(value = "user")
public class UserController {
    public static final String USER_SESSION_NAME = "user";
    @Autowired
    UserService userService;
    private static final Logger logger = LoggerFactory.getLogger(UserController.class);

    @RequestMapping(value = "register", produces = "application/json;charset=utf-8", method = RequestMethod.POST)
    @ResponseBody
    public Result<Object> register(@RequestBody User user){
        Boolean success = userService.add(user);
        return Result.create(success);
    }
    @RequestMapping(value = "login", produces = "application/json;charset=utf-8", method = RequestMethod.POST)
    @ResponseBody
    public Result<Object> login(@RequestBody User user, HttpServletRequest request) {
        logger.debug("login username:{} password:{}",user.getUserName(),user.getPassword());
        user = userService.search(user);
        if (user != null){
            HttpSession session = request.getSession();
            session.setAttribute(USER_SESSION_NAME,user);

            User u = new User();
            u.setId(user.getId());
            u.setUserName(user.getUserName());
            return Result.success();
        }
        return Result.failed();
    }

    @RequestMapping(value = "logout", produces = "application/json;charset=utf-8", method = RequestMethod.POST)
    @ResponseBody
    public Result<Object> logout(HttpServletRequest request){
        request.getSession().invalidate();
        return Result.success();
    }

    @RequestMapping(value = "delete/{id}", produces = "application/json;charset=utf-8", method = RequestMethod.POST)
    @ResponseBody
    public Result<Object> remove(@PathVariable("id") Integer id){
        Boolean success = userService.remove(id);
        return Result.create(success);
    }
    @RequestMapping(value = "password/change", produces = "application/json;charset=utf-8", method = RequestMethod.POST)
    @ResponseBody
    public Result<Object> changePassword(@RequestBody User user){
        Boolean success = userService.changeUser(user);
        return Result.create(success);
    }

}
